/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package schtohan.business;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import schtohan.entities.Journey;
import schtohan.entities.Stop;

/**
 *
 * @author Schtohan
 */
public class DbController {
    
    EntityManagerFactory emf;
    
    public DbController() {        
        emf = Persistence.createEntityManagerFactory("vasttrafikPU");   
    }
    
    public void createJourneyStops(Journey journey, List<Stop> stops)
    {
        try {
                                    
            EntityManager em = emf.createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            em.persist(journey); 
            for(Stop s : stops)
            {
                em.persist(s); 
            }   
            tx.commit();

            em.close();
        }
        catch(Exception e) {
            e.printStackTrace();        
        }
    } 
    
    public List<Journey> findJourneys(String start)
    {
        try {
            EntityManager em = emf.createEntityManager();

            String stopQuery = "select j from Journey j where j.startDate = :startDate";
            TypedQuery<Journey> tq = em.createQuery(stopQuery, Journey.class);
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
            Date startDate = sdfDate.parse(start);
            tq.setParameter("startDate", startDate, TemporalType.DATE);
            List<Journey> journeys = tq.getResultList();

            em.close();
            
            return journeys;   
        }
        catch(Exception e){
            e.printStackTrace();
        }
        
        return null;
    }
        
}
